package cup.cqzj.utils;

import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author : ruoyu
 * @date : 2023/6/6
 *  非常简单的redis并发锁 会有随机等待时间
 *  不能快速调用 有失效风险基本99% 没有绝对要求时调用
 */
@Component
@AllArgsConstructor
public class RedisLock {

	private final StringRedisTemplate redisTemplate;

	public boolean lock(String key){
		int i = RandomUtil.randomInt(1, 60);

		try {
			Thread.sleep(1000L *i);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		synchronized (this){
			Boolean aBoolean = redisTemplate.hasKey(key);
			if(Boolean.FALSE.equals(aBoolean)){
				redisTemplate.opsForValue().set(key, key, 60, TimeUnit.SECONDS);
				return true;
			}
		}
		return false;
	}
}
